package com.adcc.loadsheet.billing.task;

import com.adcc.aoc.devLib.common.log.Log;
import com.adcc.loadsheet.billing.configuration.SystemConfig;
import com.adcc.loadsheet.billing.entity.BillingBillEntity;
import com.adcc.loadsheet.billing.entity.contractuser.ContractUserEntity;
import com.adcc.loadsheet.billing.service.BillingBillService;
import com.adcc.loadsheet.billing.service.ChargeDetailService;
import com.adcc.loadsheet.billing.service.ContractUserService;
import com.adcc.loadsheet.billing.service.SystemConfigService;
import com.adcc.loadsheet.billing.util.DateTimeUtil;
import com.adcc.loadsheet.billing.util.LogUtil;
import com.adcc.loadsheet.billing.vo.SystemConfigEntityVO;
import com.google.common.base.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 自动生成帐单明细JOB
 * Created by zhaoml on 2020/9/14.
 */
@Component
@EnableScheduling
public class AutomaticProcessingBillsTask {

    @Autowired
    ContractUserService contractUserService;

    @Autowired
    ChargeDetailService chargeDetailService;

    @Autowired
    SystemConfigService systemConfigService;

    @Autowired
    BillingBillService billingBillService;

    @Autowired
    SystemConfig systemConfig;

    //监控 执行（每天凌晨1点执行一次）
//    @Scheduled(cron = "0 */1 * * * ?")
    @PostConstruct
    @Scheduled(cron = "0 0 1 * * ?")
    private void doTask(){
        try{
            //对比当日日期和配置的日期是否相同
            SystemConfigEntityVO vo = systemConfigService.getSystemConfig("automaticProcessingBillsTime");
            String systemConfigDay = (vo == null || Strings.isNullOrEmpty(vo.getConfigValue())) ? "01" : vo.getConfigValue();  //默认1号（不足10的，用0补充）
            Date dt = new Date();

            //如果某月无设置日期，记录日志“2月份无选定的自动处理帐单日期(30日)，不能生成帐单”
            //当日日期（不足10的，不用0补充，用来比较）
            int day1 = dt.getDate();
            //配置里的生成账单日期（不足10的，不用0补充，用来比较）
            int systemConfigDay1 = systemConfigDay.startsWith("0") ? Integer.valueOf(systemConfigDay.substring(systemConfigDay.indexOf("0") + 1)) : Integer.valueOf(systemConfigDay);
            //当月最后一天日期（yyyy-MM-dd）
            Date lastDay = DateTimeUtil.getLastDate(DateTimeUtil.toDateString(dt));
            //当月最后一天日期（不足10的，不用0补充，用来比较）
            int lastDay1 = lastDay.getDate();
            if(day1 == lastDay1 && day1 < systemConfigDay1){
                LogUtil.jobLog(AutomaticProcessingBillsTask.class,"doTask()",(dt.getMonth() + 1) + "月份无选定的自动处理帐单日期(" + systemConfigDay1 + "日)，不能生成帐单");
                return;
            }

            //当日日期（不足10的，用0补充）
            String day = String.format("%td", dt);
            if(!day.equals(systemConfigDay)){
                return;
            }

            //获取上个月第一天的日期
            String startDate = DateTimeUtil.getLastMonthFirstDay();
            //获取上个月最后一天的日期
            String endDate = DateTimeUtil.getLastMonthLastDay();
            //上个月月份（格式：2020-08）
            String lastMonth = DateTimeUtil.getLastMonth();
            //获取全部合同用户
            List<ContractUserEntity> contractUserEntityList = contractUserService.select(null);
            String fileName = "";   //保存到数据库的账单明细文件名称
            String fileNameUUID = "";   //生成的账单明细文件名称
            String filePathStr = systemConfig.getAutomaticProcessingBillsPath() + lastMonth + "//";   //生成的账单明细路径+文件名称
            File filePath = new File(filePathStr);
            if(!filePath.exists()){
                filePath.mkdirs();
            }
            String cost = "";
            for(ContractUserEntity contractUserEntity : contractUserEntityList){
                fileName = contractUserEntity.getUserAbbrev() + lastMonth + "月账单明细.docx";
                fileNameUUID = UUID.randomUUID().toString() + ".docx";
                //生成word格式;
                cost = chargeDetailService.wordForTask(startDate,endDate,contractUserEntity.getContractUserId(),filePathStr + fileNameUUID);
                //写入数据库
                BillingBillEntity billingBillEntity = new BillingBillEntity(contractUserEntity.getContractUserId(),lastMonth,
                        lastMonth + "//" + fileNameUUID,fileName, cost,"");
                billingBillService.edit(billingBillEntity,null);
                LogUtil.jobLog(AutomaticProcessingBillsTask.class,"doTask()","生成帐单：" + fileName);
            }
        }catch (Exception ex){
            Log.error(AutomaticProcessingBillsTask.class, "自动生成帐单明细JOB出错", ex);
            LogUtil.errorLog(AutomaticProcessingBillsTask.class, ex, "doTask()");
        }
    }
}